$(function () {
    initialPage();
    getGrid();
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

function getGrid() {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, '../role/queryAll', colunms);
    table.setExpandColumn(2);
    table.setIdField("id");
    table.setCodeField("id");
    table.setParentCodeField("parentId");
    table.setExpandAll(false);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}

var TreeGrid = {
    id: "jqGrid",
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', checkbox: true},
        {title: '角色ID	', field: 'id', visitable: false, align: 'center', valign: 'middle', width: '50px'},
        {title: '名称', field: 'name', align: 'center', valign: 'middle', width: '180px'},
       /* {title: '上级菜单', field: 'parentName', align: 'center', valign: 'middle', width: '100px'},*/
        {
            title: '状态', field: 'available', align: 'center', valign: 'middle', width: '80px',
            formatter: function (item) {
                if (item.available === 1) {
                    return '<span class="label label-success">正常</span>';
                }
                return '<span class="label label-danger">失效</span>';

            }
        },
        {title: '备注', field: 'remarks', align: 'center', valign: 'middle', width: '100px'},
    ];
    return columns;
};

//菜单树
var menu_ztree;
var menu_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: true,
        nocheckInherit: true
    }
};

//部门结构树
/*
var dept_ztree;
var dept_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};

//数据树
var data_ztree;
var data_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: true,
        nocheckInherit: true,
        chkboxType: {"Y": "", "N": ""}
    }
};
*/


var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            roleName: null
        },
        parentShow:false,
        disabled:'',
        showList: true,
        title: null,
        role: {available:1,parentId:'',parentName:''},
        ruleValidate: {
            roleName: [
                {required: true, message: '角色名称不能为空', trigger: 'blur'}
            ]
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            var roleId = TreeGrid.table.getSelectedRow();
            if(roleId.length != 0 ){ //点击某个节点来进行添加
                Id = roleId[0].id;//用作下一级的父类别id
                $.get("../role/info/" + Id, function (r) {
                    vm.role = {
                        available: 1,
                        parentId: Id,
                        parentName:r.role.name
                    };

                });
            }else {  //不选中节点来添加的
                vm.category={
                    available:1, parentId:null,parentName:null
                }
            }
            vm.disabled=true;
            vm.parentShow = true;
            vm.getMenuTree(null);
        },
        update: function () {
            var roleId = TreeGrid.table.getSelectedRow();
            if (roleId.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            console.log(roleId);
            vm.showList = false;
            vm.title = "修改";
           /* vm.getDataTree();*/
            vm.disabled=true;
            vm.parentShow = true;
            vm.getMenuTree(roleId[0].id);
        },
        del: function (event) {
            var roleIds = TreeGrid.table.getSelectedRow(), ids = [];
            if (roleIds.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.each(roleIds, function (idx, item) {
                    ids[idx] = item.id;
                });
                $.ajax({
                    type: "POST",
                    url: "../role/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.status == "00000") {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getRole: function (roleId) {
            $.get("../role/info/" + roleId, function (r) {
                vm.role = r.role;

                //勾选角色所拥有的菜单
                var permissions = vm.role.permissionSet;
                for (var i = 0; i < permissions.length; i++) {
                    var node = menu_ztree.getNodeByParam("id", permissions[i].id);
                    menu_ztree.checkNode(node, true, false);
                }

            });
        },
        saveOrUpdate: function (event) {
            //获取选择的菜单
            var nodes = menu_ztree.getCheckedNodes(true);
            var permissionSet = new Array();
            for (var i = 0; i < nodes.length; i++) {
                permissionSet.push(nodes[i]);
            }
            vm.role.permissionSet = permissionSet;

           /* var url = vm.role.roleId == null ? "../sys/role/save" : "../sys/role/update";*/
           var url = "../role/saveOrUpdate"
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.role),
                success: function (r) {
                    if (r.status === "0000") {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        getMenuTree: function (roleId) {
            //加载菜单树
            $.get("../permission/role/list.json", function (r) {
                menu_ztree = $.fn.zTree.init($("#menuTree"), menu_setting, r.permissionList);
                //展开所有节点
                menu_ztree.expandAll(true);

                if (roleId != null) {
                    vm.getRole(roleId);
                }
            });
        },
        /*getDataTree: function (roleId) {
            //加载菜单树
            $.get("../sys/dept/list", function (r) {
                data_ztree = $.fn.zTree.init($("#dataTree"), data_setting, r.list);
                //展开所有节点
                data_ztree.expandAll(true);
            });
        },
        getDept: function () {
            //加载部门树
            $.get("../sys/dept/list", function (r) {
                dept_ztree = $.fn.zTree.init($("#deptTree"), dept_setting, r.list);
                var node = dept_ztree.getNodeByParam("deptId", vm.role.deptId);
                if (node != null) {
                    dept_ztree.selectNode(node);

                    vm.role.deptName = node.name;
                }
            })
        },
        deptTree: function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = dept_ztree.getSelectedNodes();
                    //选择上级部门
                    vm.role.deptId = node[0].deptId;
                    vm.role.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },*/
        reload: function (event) {
            /*vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'roleName': vm.q.roleName},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');*/
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    },
   /* created: function () {

    }*/
});